<template>
<van-address-edit
  :area-list="areaList"
  :address-info="addressInfo"
  show-postal
  show-delete
  show-set-default
  show-search-result
  @save="onSave"
  @delete="onDelete"
  style="padding-bottom: 50px;"
/>
</template>

<script>
import qs from 'qs';
import { AddressEdit, Toast } from 'vant';
import ajaxVant from '../../../utils/ajaxVant';
import auth from '../../../utils/auth';
import areaList from '../../../mock/area';

export default {
  components: {
    [AddressEdit.name]: AddressEdit
  },
  data() {
    return {
      areaList,
      addressInfo: {}
    };
  },
  methods: {
    selectActionsheet(action) {
      this.formFields.type = action.type;
      this.currentActionsheet.name = action.name;
      this.showActionsheet = false;
    },
    getData() {
      var _this = this;
      auth.getToken().then(function(token) {
        ajaxVant.get('/user/address/' + _this.$route.params.id + '?token=' + token).then(function(data) {
          if (data !== false) {
            _this.addressInfo = data.user_address;
            if (data.user_address['is_default'].toString() === '1') {
              _this.addressInfo['is_default'] = true;
            } else {
              _this.addressInfo['is_default'] = false;
            }
          }
        });
      });
    },
    onSave(val) {
      var _this = this;
      auth.getToken().then(function(token) {
        ajaxVant.put('/user/address/' + _this.$route.params.id + '?token=' + token, qs.stringify(val)).then(function(data) {
          if (data !== false) {
            Toast(data.msg);

            setTimeout(() => {
              Toast.clear();
              _this.$router.push({ name: 'userAddress' });
            }, 1000);
          }
        });
      });
    },
    onDelete(item) {
      var _this = this;
      auth.getToken().then(function(token) {
        ajaxVant.delete('/user/address/' + _this.$route.params.id + '?token=' + token).then(function(data) {
          if (data !== false) {
            Toast(data.msg);

            setTimeout(() => {
              Toast.clear();
              _this.$router.push({ name: 'userAddress' });
            }, 1000);
          }
        });
      });
    }
  },
  mounted() {
    this.getData();
  }
};

</script>